package com.qili.service.it.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.CurrentUser;
import com.qili.entity.base.FormType;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.supervisor.SupervisorProjectForms;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.entity.sys.SysLog;
import com.qili.mapper.search.ItFormMapper;
import com.qili.mapper.supervisor.SupervisorFileMapper;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.util.BeanUtil;
import com.qili.util.CommonUtil;
import com.qili.util.DateUtil;
import com.qili.util.ReType;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import java.io.File;
import java.util.*;

/**
 * @author liuyang
 * @date 2020/11/3
 * @description     专利表单具体业务类
 */
@Log
@Service("JiChengDianLuFormService")
public class JiChengDianLuFormServiceImpl extends FormBaseServiceImpl{

    private static final Integer FILE_COUNT = 1;

    @Autowired
    ItFormMapper itFormMapper;

    @Autowired
    SysLogMapper sysLogMapper;

    @Autowired
    private SupervisorFileMapper supervisorFileMapper;

    public void saveFormData(SupervisorProjectFromsDTO forms, boolean ifNew) {
        //该表单没有表体,闲着就好
    }

    /**
     * 保存表单文件
     * @param forms
     * @param ifNew
     */
    public void saveFormFile(SupervisorProjectFromsDTO forms, boolean ifNew) {
        //说明书
        ArrayList<String> jiShuJiaoDiFileIds = forms.getStrList2();

        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //编辑表单页面不需要移动文件，只是操作删除数组:
            ArrayList<String> strList9 = forms.getStrList9();
            if(CollectionUtil.isNotEmpty(strList9)){
                for(String delFileId:strList9){
                    //设置为回收站状态:
                    SupervisorFile delFile = new SupervisorFile();
                    delFile.setId(delFileId);
                    delFile.setDeleteState("2");
                    delFile.setDeleteUser(CommonUtil.getUserId());
                    delFile.setDeleteDate(DateUtil.getCurrentDateString());
                    dicService.updateByPrimaryKeySelective(delFile);
                    SupervisorFile supervisorFile = supervisorFileMapper.selectByPrimaryKey(delFileId);
                    if(supervisorFile!=null){
                        insertFileLog(supervisorFile.getFileName());
                    }
                }
            }
        }else{
            //这里是新建表单逻辑:
            //新建表单核心文件夹:
            String formCode = forms.getSpfF30();
            FormType formType = FormType.getFormType(formCode);
            //生成表单核心文件夹路径：（例如:/书著/2021_001_xx书著）
            //该方法执行后,会把核心文件设置为formDto的Obj1对象
            createCenterDic(forms);
            SupervisorFile centFile = (SupervisorFile) forms.getObj1();
            if(CollectionUtil.isNotEmpty(jiShuJiaoDiFileIds)){
                //这里面存放的是临时文件id:
                for(String shuzhuFileId : jiShuJiaoDiFileIds){
                    SupervisorFileTemp supervisorFileTemp = fileTempService.selectByPrimaryKey(shuzhuFileId);
                    //1.移动操作系统文件 newFile为移动后的文件
                    File newFile = moveTempFile(supervisorFileTemp, forms);
                    //2.复制数据到正式文件表
                    //更改url
                    supervisorFileTemp.setUrl(newFile.getPath());
                    SupervisorFile newSupervisorFile = new SupervisorFile();
                    BeanUtil.copyNotNullBean(supervisorFileTemp,newSupervisorFile);
                    newSupervisorFile.setZskfileType("2");
                    newSupervisorFile.setDeleteState("1");
                    //表单中的每一个文件都指向该核心文件
                    newSupervisorFile.setLinkId(centFile.getId());
                    fileService.insertFile(newSupervisorFile,(SupervisorFile) forms.getObj1());
                    //3.删除临时文件表
                    fileTempService.deleteByPrimaryKey(shuzhuFileId);
                }
            }
        }
    }

    public void insertFileLog(String filename) {
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType("DEL");
        sysLog.setText("删除文件");
        sysLog.setParam("参数:文件名称：" + filename);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser user = CommonUtil.getUser();
        sysLog.setUserName(user.getUsername());
        sysLogMapper.insert(sysLog);
    }

    /**
     * 获取表单数据
     * @param formTypeCode
     * @param formDto
     * @param model
     */
    public void getFormData(String formTypeCode, SupervisorProjectFromsDTO formDto, Model model) {
        //木有东西
    }

    public ReType selectFormBook(SupervisorProjectFromsDTO formInfo, String page, String limit) {
        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
            formInfo.setSpfF1("%"+formInfo.getSpfF1()+"%");
        }
        Page<SupervisorProjectFromsDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<SupervisorProjectForms> supervisorProjectForms = itFormMapper.selectJCDLBTTZ(formInfo);
        List<SupervisorProjectFromsDTO> formDto = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(supervisorProjectForms)){
            formDto = getFormDto(formInfo.getSpfF30(), supervisorProjectForms);

        }
        return new ReType(tPage.getTotal(),formDto);
    }

    private List<SupervisorProjectFromsDTO> getFormDto(String formTypeCode,List<SupervisorProjectForms> supervisorProjectForms) {
        List<SupervisorProjectFromsDTO> formsDtoList = new ArrayList<SupervisorProjectFromsDTO>();
        for(int i=0;i<supervisorProjectForms.size();i++){
            SupervisorProjectForms aForm = supervisorProjectForms.get(i);
            SupervisorProjectFromsDTO aDto = changeToDto(aForm);
            getFormData(formTypeCode,aDto,null);
            setFormFiles(formTypeCode,aDto);
            aDto.setFileInd(i+1);
            formsDtoList.add(aDto);
        }
        return formsDtoList;
    }

    /**
     * 获取集成电路布图统计表格数据:
     *
     *  //布图设计姓名
     * 		var name = $('#name').val();
     * 		var start = $('#date_start'+defaultTabInd).val();
     * 		var end = $('#date_end'+defaultTabInd).val();
     * 		var jsondata = {
     * 			spfF1:name,
     * 			obj1: start,
     * 			obj2: end
     *                };
     * 		return jsondata;
     * @return
     */
    @Override
    public ReType selectFormStatisticsTableData(String formTypeCode, SupervisorProjectFromsDTO formInfo, String index, String page, String limit) {
        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
            formInfo.setSpfF1("%"+formInfo.getSpfF1()+"%");
        }
        Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<Map<String,Object>> resultMap = itFormMapper.getJiChengDianLuStatistics0(formInfo);
        //获取根据符合条件的年份列表:
        return new ReType(objects.getTotal(),resultMap);
    }
}
